package org.ricks.actor;

import org.ricks.common.ThreadNameFactory;
import org.ricks.utils.RandomUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author chenwei
 * @Description:网络消息actor & db actor & log actor
 * @date 2022/9/2113:18
 */
public class ActorMgr {

    private static final String EXECUTOR = "work";
    private static final String LOG_EXECUTOR = "log";

    private static int threadNum = Runtime.getRuntime().availableProcessors() * 2;

    //业务线程
    private static final Actor[] actors = ActorMgr.get().createActors(threadNum,EXECUTOR);
    //log actor
    private static final Actor logActor =ActorMgr.get().createActor(LOG_EXECUTOR);
    
    /**
     * @Description: 创建actor入口 ，供应给工程使用
     * @param threadNum 线程数量
     * @return Actor[]
     * @author chenwei
     * @date 2022/11/23 14:21
     */
    public Actor[] createActors(int threadNum,String name) {
        Actor[] actors = new Actor[threadNum];
        ExecutorService executors = Executors.newFixedThreadPool(threadNum,new ThreadNameFactory(0,name));
        for (int i = 0; i < threadNum; i++) {
            actors[i] = new Actor(executors);
        }
        return actors;
    }

    public Actor createActor(String name) {
        ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadNameFactory(0,name));
        Actor actor = new Actor(executor);
        return actor;
    }

    private static class SingleCase {
        public static final ActorMgr INSTANCE = new ActorMgr();
    }

    private ActorMgr() {

    }

    public static ActorMgr get() {
        return ActorMgr.SingleCase.INSTANCE;
    }

    public Actor get(long index) {
        return actors[(int) (Math.abs(index) % actors.length)];
    }

    public Actor getRandom() {
        return actors[RandomUtil.randomInt(threadNum)];
    }

    public Actor getLogActor() {
        return logActor;
    }
}
